package com.sync.hkmjsyncdata.task;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.sync.hkmjsyncdata.config.isecurecenter.IsecureCenterUtilsService;
import com.sync.hkmjsyncdata.pojo.po.HkPerson;
import com.sync.hkmjsyncdata.pojo.po.HkVehicle;
import com.sync.hkmjsyncdata.service.IHkPersonService;
import com.sync.hkmjsyncdata.service.IHkVehicleService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SyncMjVehicle {

    static final String PAGE_NO_KEY = "pageNo";
    static final String PAGE_SIZE_KEY = "pageSize";

    @Resource
    IsecureCenterUtilsService centerUtilsService;

    @Resource
    IHkVehicleService vehicleService;


    /**
     * 同步海康人员
     */
    @XxlJob("SyncMjVehicle")
    public void SyncMjVehicleData() {
        XxlJobHelper.log("开始同步海康门禁车辆信息");
        List<HkVehicle> allResult = vehicleService.list();
        if (ObjectUtils.isNotEmpty(allResult)) {
            XxlJobHelper.log("数据库已有海康车辆信息：{}条", allResult.size());
        }

        List<HkVehicle> newVehicles = new ArrayList<>();
        SyncMjVehicleDataByHk(1,newVehicles);
        bulidMjPersonInfo(allResult, newVehicles);


    }


    private void SyncMjVehicleDataByHk(int pageNo, List<HkVehicle> newVehicles) {
        JSONObject orgParams = new JSONObject();
        orgParams.put(PAGE_NO_KEY, pageNo);
        orgParams.put(PAGE_SIZE_KEY, 1000);
        String resultInfo = centerUtilsService.doPost("/api/resource/v2/vehicle/advance/vehicleList", orgParams.toJSONString());
        if (StringUtils.isNotBlank(resultInfo)) {
            JSONObject orgResult = JSON.parseObject(resultInfo);
            JSONObject orgData = orgResult.getJSONObject("data");
            if (ObjectUtils.isNotEmpty(orgData) && ObjectUtils.isNotEmpty(orgData.getJSONArray("list"))) {
                JSONArray list = orgData.getJSONArray("list");
                for (int i = 0; i < list.size(); i++) {
                    JSONObject vehicleInfo = list.getJSONObject(i);
                    newVehicles.add(new HkVehicle()
                            .setCphnbsht(vehicleInfo.getString("plateNo"))
                            .setPhone("")
                            .setZjrId(vehicleInfo.getString("personName"))
                            .setDwOrgNo(vehicleInfo.getString("regionName"))
                            .setRcclTyp(1)
                            .setOpTyp(1));
                }
                if(ObjectUtils.isNotEmpty(list)){
                    SyncMjVehicleDataByHk(pageNo+1,newVehicles);
                }
            } else {
                XxlJobHelper.log("同步海康门禁车辆信息失败");
            }
        }



    }


    private void bulidMjPersonInfo(List<HkVehicle> allResult, List<HkVehicle> newPersons) {

        Map<String, HkVehicle> oldVehicleMap = allResult.stream().collect(Collectors.toMap(HkVehicle::getCphnbsht, point -> point, (a, b) -> b));
        if (ObjectUtils.isEmpty(oldVehicleMap)) {
            vehicleService.saveBatch(newPersons);
        } else {
            List<HkVehicle> addHkVehicleList = new ArrayList<>();
            List<HkVehicle> updateVehicleList = new ArrayList<>();
            List<String> ids = new ArrayList<>();
            newPersons.forEach(vehicle -> {
                ids.add(vehicle.getCphnbsht());
                HkVehicle oldVehicle = oldVehicleMap.get(vehicle.getCphnbsht());
                if (ObjectUtils.isEmpty(oldVehicleMap.get(vehicle.getCphnbsht()))) {
                    addHkVehicleList.add(vehicle);
                } else {
                    updateVehicleList.add(vehicle.setOpTyp(oldVehicle.getOpTyp() == 4 ? 2 : oldVehicle.getOpTyp()));
                }
            });
            List<HkVehicle> deletevehicleList = allResult.stream().filter(vehicle -> (!ids.contains(vehicle.getCphnbsht())) && vehicle.getOpTyp() == 4).toList();
            deletevehicleList.forEach(nreg -> nreg.setOpTyp(3));
            XxlJobHelper.log("新增海康车辆信息：{}条", addHkVehicleList.size());
            vehicleService.saveBatch(addHkVehicleList);
            XxlJobHelper.log("修改海康车辆信息：{}条", updateVehicleList.size());
            vehicleService.updateBatchById(updateVehicleList);
            XxlJobHelper.log("删除海康车辆信息：{}条", deletevehicleList.size());
            vehicleService.updateBatchById(deletevehicleList);
        }


    }

}
